package core

import (
	"github.com/solarlune/resolv"
)

type ProjectileMovement struct {
	Sprite       ISprite
	Lifetime     int
	Velocity     resolv.Vector
	Speed        float64
	Acceleration resolv.Vector // 加速度向量
	Gravity      resolv.Vector
	timer        float64
}

type ProjectileMovementOption struct {
	Lifetime     int
	Direction    resolv.Vector
	Speed        float64
	Acceleration resolv.Vector // 加速度向量
	Gravity      resolv.Vector
}

func NewProjectileMovement(sprite ISprite, option ProjectileMovementOption) *ProjectileMovement {
	normalizedDir := option.Direction.Unit()

	p2 := &ProjectileMovement{
		Lifetime:     option.Lifetime,
		Velocity:     normalizedDir.Scale(option.Speed),
		Acceleration: option.Acceleration, // 加速度向量
		Gravity:      option.Gravity,
		Speed:        option.Speed,
	}
	p2.Sprite = sprite
	// if p2.Lifetime > 0 {
	// 	p2.StartTimer(float64(p2.Lifetime), func() {
	// 		sprite.Destory()
	// 	}, true)
	// }
	return p2
}

func (p *ProjectileMovement) MoveVec(vec resolv.Vector) {
	p.Sprite.MoveVec(vec)
}

// const (
// 	GravityAcceleration = 5
// 	DegreesToRadians    = math.Pi / 180
// )

func (p *ProjectileMovement) Update(dt float64) {
	//p.UpdateTimer(dt)
	// 生命周期计时
	if p.Lifetime > 0 {
		p.timer += dt
		if p.timer >= float64(p.Lifetime) {
			p.Sprite.Destory()
			return
		}
	}

	// 计算合成加速度（基础加速度 + 重力）
	totalAccel := p.Acceleration.Add(p.Gravity)

	// 更新速度：v = v0 + a*t
	p.Velocity = p.Velocity.Add(totalAccel.Scale(dt))

	// 计算位移：s = v*dt + 0.5*a*dt²（更精确的积分方式）
	displacement := p.Velocity.Scale(dt).
		Add(totalAccel.Scale(0.5 * dt * dt))

	// 移动精灵
	p.Sprite.MoveVec(displacement)
}

// func (p *ProjectileMovement) GetProjectileMovement() *ProjectileMovement {
// 	return p
// }
